package com.origin.app.page.main.fragment.home

import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import androidx.recyclerview.widget.LinearLayoutManager
import com.amap.api.maps.AMap
import com.amap.api.maps.CameraUpdateFactory
import com.amap.api.maps.model.CameraPosition
import com.amap.api.maps.model.LatLng
import com.amap.api.maps.model.Marker
import com.jeremyliao.liveeventbus.LiveEventBus
import com.origin.app.R
import com.origin.app.bean.CompanyPointBean
import com.origin.app.databinding.FragmentHomeBinding
import com.origin.app.databinding.FragmentMineBinding
import com.origin.app.dialog.CompanyListDialog
import com.origin.app.page.location_records.LocationRecordsActivity
import com.origin.app.page.map.AppMapViewModel
import com.origin.app.page.map.adapter.NavAdapter
import com.origin.app.service.SignalrService
import com.origin.app.utils.MapUtils
import com.origin.app.utils.NetAppUtils
import com.origin.baselibrary.fragment.ViewModelFragment
import com.origin.uilibrary.xrecycleview.adapter.BaseRecycleAdapter
import com.origin.utils.log.LogUtils
import com.origin.utils.statusBar.StatusBarUtil
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach

class HomeFragment : ViewModelFragment<FragmentHomeBinding, AppMapViewModel>(R.layout.fragment_home), View.OnClickListener  ,
    BaseRecycleAdapter.OnItemClickListener<CompanyPointBean>{


    private val navAdapter: NavAdapter by lazy {
        NavAdapter(viewModel.navList, this@HomeFragment.mContext)
    }
    private   val slideInBottomAnimation: Animation by lazy {
        AnimationUtils.loadAnimation(this@HomeFragment.mContext, R.anim.slide_in_bottom)
    }
    private   val slideOutBottomAnimation: Animation by lazy {
        AnimationUtils.loadAnimation(this@HomeFragment.mContext, R.anim.slide_out_bottom)
    }

    private fun checkBtnState(tag: Int) {
        if (viewModel.selectIndex.get() != tag) {
            MapUtils.showMarker(tag)
            viewModel.selectIndex.set(tag)
            return
        } else {
            MapUtils.showAllMarker(tag)
            viewModel.selectIndex.set(0)
        }
    }
    
    override fun onClick(view: View?) {
        if (view == null) {
            return;
        }

        LogUtils.__e("选择正常内容===>")

        if (view == mBinding.btn) {
            CompanyListDialog(viewModel.companyBeanList, this@HomeFragment.mContext) {
                viewModel.checkCompanyPoint()
            }.show(this@HomeFragment.activity!!.supportFragmentManager, "CompanyListDialog")
            return
        }
        if (view == mBinding.btnNormal) {
            checkBtnState(1);
            return
        }
        if (view == mBinding.btnException) {
            checkBtnState(2);
            return
        }
        if (view == mBinding.btnOffline) {
            checkBtnState(3);
            return
        }
        if (view == mBinding.btnNotOnline) {
//            checkBtnState(4);
            viewModel.resetNavNotOnlineList()
            navAdapter.notifyDataSetChanged()
            mBinding.homeId.openDrawer(Gravity.START)
            return
        }
        if (view == mBinding.imgUser) {
            viewModel.resetNavList()
            navAdapter.notifyDataSetChanged()
            mBinding.homeId.openDrawer(Gravity.START)
            return
        }
        if(view==mBinding.bottomMarkerPointInfo.tvTrack){
            LogUtils.__e("选择内容    ${selectCompanyPointBean.phone}")
            LocationRecordsActivity.launcher(selectCompanyPointBean)
            return
        }
        if (view==mBinding.bottomMarkerPointInfo.tvFence){
            viewModel.getTaskIdByPolygon(selectCompanyPointBean,mBinding.mapView.map)
            return
        }
    }

    var isFirst = true;
    override fun onResume() {
        super.onResume()
        mBinding.mapView.onResume()
        if (isFirst) {
            isFirst = false;
            viewModel.getCompanyListUrl()
        }

    }
    override fun initUI() {
        mBinding.appMapViewModel = viewModel


        mBinding.btn.setOnClickListener(this@HomeFragment)
        LogUtils.__e("HomeFragment===== initUI ")
        mBinding.btnNormal.setOnClickListener(this@HomeFragment)
        mBinding.btnException.setOnClickListener(this)
        mBinding.btnOffline.setOnClickListener(this)
        mBinding.btnNotOnline.setOnClickListener(this)
        mBinding.imgUser.setOnClickListener(this)
        // bottom_marker_point_info
        mBinding.bottomMarkerPointInfo.tvTrack.setOnClickListener(this)
        mBinding.bottomMarkerPointInfo.tvFence.setOnClickListener(this)
        mBinding.navList.layoutManager = LinearLayoutManager(this@HomeFragment.mContext)
        mBinding.navList.adapter = navAdapter
        navAdapter.mItemClickListener=this
        mBinding.selectCompanyPointBean = selectCompanyPointBean
        mBinding.companyPointBean= CompanyPointBean().apply {
            this.name="名称";
            this.company_Name="机构"
        }
        SignalrService.launcher(this@HomeFragment.activity!!)
        LiveEventBus.get("location", CompanyPointBean::class.java).observe(this){
            if(mBinding.homeId.isOpen){
                viewModel.imRefreshNavList(it)
            }
            // 刷新全部数据
            viewModel.imRefreshMarkerList(it)
        }


        viewModel.refreshNavListMutableLiveData
            .debounce(500L)
            .onEach {
                LogUtils.__e("navAdapter 刷新x")
                navAdapter.notifyItemRangeChanged(0, viewModel.navList.size)
            }.launchIn(this)


        viewModel.refreshListMutableSharedFlow
            .debounce(500L)
            .onEach {
//                LogUtils.__e("数值 刷新x")
                viewModel.refreshNum()
            }.launchIn(this)

        viewModel.refreshListMutableLiveData.observe(this) {
            showLocationMarker()
            viewModel.refreshNum()
            // 发送server
            SignalrService.addGroups(this@HomeFragment.activity!!, viewModel.companyCodeList)
        }
        viewModel.refreshNetPointInfoMutableLiveData.observe(this){
            selectCompanyPointBean.refreshPic(NetAppUtils.staticFileHost+it.photo)
            selectCompanyPointBean.phone=it.phone
        }
        
    }


    private fun showLocationMarker() {

        val markers = mutableListOf<Marker>()
        mBinding.mapView.map.clear()
        MapUtils.clearMarkerMap()
        viewModel.companyPointList.forEach {
            val marker: Marker =
                mBinding.mapView.map.addMarker(
                    MapUtils.getMarker(it.equipmentState, it.isCard)
                        .position(LatLng(it.gcJ02.lat, it.gcJ02.lng))
                        .title(it.name)
//                    .snippet("DefaultMarker")
                )
            marker.`object`=it
            MapUtils.classificationMarker(it.equipmentState, marker)
            markers.add(marker)
        }


        MapUtils.fitMarkersToBounds(markers, mBinding.mapView.map);
        mBinding.mapView.map.setOnMarkerClickListener(object :
            AMap.OnMarkerClickListener {
            override fun onMarkerClick(master: Marker?): Boolean {
                return  showBottomInfo(master)
            }

        })
        mBinding.mapView.map.setOnMapClickListener {
            LogUtils.__e("点击了 地图")
            if(actionMaskClick){
                actionMaskClick=false
                return@setOnMapClickListener
            }
            mBinding.bottomMarkerPointInfo.dialogBottomMarkerPointInfoRoot.startAnimation(
                slideOutBottomAnimation
            )
            mBinding.bottomMarkerPointInfo.dialogBottomMarkerPointInfoRoot.visibility =
                View.GONE
        }

    }
    private var actionMaskClick=false
    private fun showBottomInfo(master: Marker?):Boolean{
        LogUtils.__e("点击了 Marker")
        actionMaskClick=true
        viewModel.viewModelSuspend{
            delay(500)
            actionMaskClick=false;
        }
        if(master==null){
            return false;
        }
        var bean= master.`object`;

        if (bean !is CompanyPointBean){
            return false;
        }
        // bottom_marker_point_info
        selectCompanyPointBean.refresh(bean)
        viewModel.getNetPointInfo(bean)
        if( mBinding.bottomMarkerPointInfo.dialogBottomMarkerPointInfoRoot.visibility!=View.VISIBLE){
            mBinding.bottomMarkerPointInfo.dialogBottomMarkerPointInfoRoot.visibility=View.VISIBLE
            // 加载动画
            mBinding.bottomMarkerPointInfo.dialogBottomMarkerPointInfoRoot.startAnimation(slideInBottomAnimation)
        }
        // 应用动画
        return false;
    }
    
    private val selectCompanyPointBean=CompanyPointBean()
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        mBinding.mapView.onCreate(savedInstanceState)
    }
    
    override fun showHintFragment(isVisibleToUser: Boolean) {
    }

    override fun onItemClick(position: Int, item: CompanyPointBean, view: View?) {
        val mapMarkerBean = MapUtils.getCompanyPointBeanByCode(item.in_Code)
        mBinding.homeId.closeDrawer(Gravity.START)
        val mAMap= mBinding.mapView.map
        val cameraPosition = CameraPosition(LatLng(item.gcJ02.lat, item.gcJ02.lng), 25f, 0f, 0f)
        val cameraUpdate = CameraUpdateFactory.newCameraPosition(cameraPosition)
        mapMarkerBean?.showInfoWindow()
        mAMap.moveCamera(cameraUpdate)
        showBottomInfo(mapMarkerBean)
    }
}